package com.qianfeng.vhly.youshare.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.qianfeng.vhly.youshare.R;
import com.qianfeng.vhly.youshare.adapters.StoreCoreAdapter;
import com.qianfeng.vhly.youshare.model.Product;
import com.qianfeng.vhly.youshare.tasks.ProductListTask;
import com.qianfeng.vhly.youshare.tasks.TaskProcessor;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/2/5
 * Email: vhly@163.com
 */
public class StoreCoreFragment extends Fragment implements TaskProcessor {

    /**
     * 用于标识是否已经加载过一次数据了。
     */
    private boolean hasFirstLoad = false;
    private StoreCoreAdapter adapter;
    private LinkedList<Product> products;

    public StoreCoreFragment() {
        // Default constructor do not delete this method.
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_store_core, container, false);

        ListView listView = (ListView) ret.findViewById(R.id.store_core_product_list);
        if (listView != null) {
            // TODO 设置Adapter
            products = new LinkedList<Product>();
            adapter = new StoreCoreAdapter(getActivity(), products);

            listView.setAdapter(adapter);
        }

        if (!hasFirstLoad) {
            ProductListTask task = new ProductListTask(this);
            //     参数:  categoryId, size
            task.execute("1", "10");
        }

        return ret;
    }

    /**
     * 异步任务更新UI的回调方法
     *
     * @param result
     */
    @Override
    public void processResult(JSONObject result) {
        // TODO 显示商品列表

        if (result != null) {
            Log.d("YouShare", "Core Product List: " + result);
            hasFirstLoad = true;

            try {
                int code = result.getInt("code");

                if (code == 1) {
                    // TODO 正确数据，需要解析

                    JSONObject msg = result.getJSONObject("msg");

                    JSONObject data = msg.getJSONObject("data");

                    Iterator keys = data.keys();

                    List<Product> productList = new LinkedList<Product>();

                    while (keys.hasNext()) {
                        Object key = keys.next();
                        JSONObject jsonObject = data.getJSONObject((String) key);
                        Product product = new Product();
                        product.parseJSON(jsonObject);
                        productList.add(product);
                    }

                    // 注意，如果是刷新数据，那么products成员变量就需要清空，然后
                    //      用productList里面的内容添加到 products中，相当于ListView重新加载
                    // 如果需要实现，“加载更多”的操作，那么就不能够清空 List，而是直接添加


                    products.addAll(productList);

                    adapter.notifyDataSetChanged();

                } else {
                    String msg = result.getString("msg");
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }
}